<?php

defined('SYSPATH') or die('No direct script access.');

class Controller_Book extends Controller_Autorization {

	public function before() {
		parent::before();
		$this->_json = FALSE;
		$this->_short = FALSE;
		$this->_data['exchange'] = Model::factory('Book')->get_config('exchange');
	}

	public function after() {
		if ($this->_json === TRUE) {
			$this->response->headers('Content-Type', 'text/json charset=utf-8');
			$this->_body = json_encode($this->_body);
		}
		elseif ($this->_short === FALSE) {

			$this->_body = View::factory('blocks/header_bs', $this->_data) .
					View::factory('blocks/header_bs_menu', $this->_data) .
					$this->_body .
					View::factory('blocks/footer_bs');
		}
		$this->response->body($this->_body);
		parent::after();
	}

	public function action_index() {
		$this->action_orders();
	}

	public function action_balance(){
		// если метод запроса POST и выполнен с использованием AJAX
		if ($this->request->method() == Request::POST AND $this->request->is_ajax() AND $this->request->post('action') == 'balance') {
			$this->_json = TRUE;
			$data['userid'] = (int)$this->request->post('userid');
			$data['value'] = (int)$this->request->post('value');
			$data['orderid'] = (int)$this->request->post('orderid');
			if (empty($data['userid']) OR empty($data['value'])){
				$this->_body = array('status' => 'err','type' => 'balance');
			}
			else {
				$data['time'] = time();
				if ($this->request->post('type')=='debit'){
					$item = Model::factory('Book')->change_balance($data);
				}
				elseif ($this->request->post('type')=='credit'){
					$data['value'] = $data['value']*-1;
					$item = Model::factory('Book')->change_balance($data);
				}
				$this->_body = array('status' => 'ok','type' => 'balance','load'=>URL::site('book/balance'));
			}
		}
		elseif ($this->request->is_ajax()){
			$this->_short = TRUE;
			if ($this->user->username!='root'){
				$userid = $this->user->id;
			}
			$this->_data['balances'] = Model::factory('Book')->get_balance($userid);
			$this->_body = View::factory('Book/balance/table', $this->_data);
		}
		elseif ($this->_data['orderid']!=NULL){
			$this->_data['balances'] = Model::factory('Book')->get_balance($this->_data['orderid']);
			$this->_data['balance_log'] = Model::factory('Book')->get_balance_log($this->_data['orderid']);
			$this->_data['balance_table'] = View::factory('Book/balance/tablelog', $this->_data);
			$this->_body = View::factory('Book/balance', $this->_data);
		}
		else {
			$userid = NULL;
			if ($this->user->username!='root'){
				$userid = $this->user->id;
			}
			$this->_data['balances'] = Model::factory('Book')->get_balance($userid);
			$this->_data['balance_table'] = View::factory('Book/balance/table', $this->_data);
			$this->_body = View::factory('Book/balance', $this->_data);
		}
	}

	public function action_items() {
		// если метод запроса POST и выполнен с использованием AJAX
		if ($this->request->method() == Request::POST AND $this->request->is_ajax() AND $this->request->post('action') == 'delete') {
			$this->_json = TRUE;
			$item = Model::factory('Book')->get_data('items', NULL, $this->_data['orderid'], TRUE);
			Model::factory('Book')->delete($this->_data['action'], array('id' => $this->_data['orderid']));
			$this->recalculate($item['orderid']);
			$this->_body = array('status' => 'ok');
		}
		elseif ($this->request->method() == Request::POST AND $this->request->is_ajax() AND $this->request->post('action') == 'deleteimg' AND $this->request->post('file')!='') {
			$this->_json = TRUE;
			$del = $this->request->post('file');
			$item = Model::factory('Book')->get_data('items', NULL, $this->_data['orderid'], TRUE);
			$files = explode(',',trim($item['files'],','));
			unset($item);
			$files = array_unique($files);
			foreach($files as $k=>&$file){
				$file = trim($file);
				if (empty($file) OR $file==$del){
					unset($files[$k]);
				}
			}
			$this->deleteimg($del);
			$data['files'] = implode(',',$files);
			Model::factory('Book')->update($this->_data['action'], array('id' => $this->_data['orderid']), $data);
			$item['status'] = 'ok';
			$this->_body = $item;
		}
		elseif ($this->request->method() == Request::POST AND $this->request->is_ajax() AND $this->request->post('action') == 'edit') {
			$this->_json = TRUE;
			$item = Model::factory('Book')->get_data('items', NULL, $this->_data['orderid'], TRUE);
			$this->recalculate($item['orderid']);
			$item['status'] = 'ok';
			$this->_body = $item;
		}
		elseif ($this->request->method() == Request::POST AND $this->request->is_ajax() AND $this->request->post('action') == 'status') {
			$this->_json = TRUE;
			if (Model::factory('Book')->update($this->_data['action'], array('id' => $this->_data['orderid']), array('status' => $this->request->post('status')))) {
				$this->_data['item'] = Model::factory('Book')->get_data('items', NULL, $this->_data['orderid'], TRUE);
				$this->recalculate($this->_data['item']['orderid']);
				$this->_data['rows'] = Model::factory('Book')->get_data('items', NULL, $this->_data['item']['orderid']);
				$this->_data['all_cost'] = 0;
				foreach ($this->_data['rows'] as &$row) {
					$this->_data['all_cost'] += ($row['quantity'] > 0 AND $row['status'] != 'нет в наличии') ? $row['delivery'] + $row['quantity'] * $row['cost'] : 0;
				}
				$info = 'full';
				if ($this->_data['role']['name'] == 'performer') {
					$info = 'short';
				}
				$json = array(
					'cost' => $this->_data['all_cost'],
					'status' => 'ok',
					'info' => $info,
				);
				$this->_body = $json;
			}
			else {
				$this->_body = array('status' => 'error');
			}
		}
		elseif ($this->request->method() == Request::POST AND $this->request->is_ajax()) {
			$this->_json = TRUE;
			// проверяем полученные данные
			$post = Validation::factory($this->request->post());
			$post->rule('quantity', 'Valid::digit');
			$files = explode(',', trim($this->request->post('filesname'), ','));
			$files = array_unique($files);
			foreach($files as $k=>&$file){
				$file = trim($file);
				if (empty($file) OR $file==$del){
					unset($files[$k]);
				}
			}
			$data = array(
				'orderid' => $this->request->post('orderid'),
				'name' => $this->request->post('name'),
				'link' => $this->request->post('link'),
				'quantity' => $this->request->post('quantity'),
				'delivery' => $this->request->post('delivery'),
				'cost' => $this->request->post('cost'),
				'files' => implode(',', $files),
				'comment' => $this->request->post('comment')
			);
			// если проверка пройдена и card_id пустой (первое сохранение)
			if ($post->check() AND $this->request->post('id', NULL) == NULL) {
				$query = DB::insert('items', array(
							'orderid',
							'name',
							'link',
							'quantity',
							'delivery',
							'cost',
							'files',
							'comment'
								)
						)
						->values(
								array(
									$this->request->post('orderid'),
									$this->request->post('name'),
									$this->request->post('link'),
									$this->request->post('quantity'),
									$this->request->post('delivery'),
									$this->request->post('cost'),
									trim(implode(',', $files),','),
									$this->request->post('comment')
								)
						)
						->execute();
			}
			elseif ($post->check()) {
				Model::factory('Book')->update($this->_data['action'], array('id' => $this->request->post('id')), $data);
			}
			$this->recalculate($this->request->post('orderid'));
			$this->_data['rows'] = Model::factory('Book')->get_data('items', NULL, $this->request->post('orderid'));
			$this->_data['all_cost'] = 0;
			foreach ($this->_data['rows'] as &$row) {
				$this->_data['all_cost'] += ($row['quantity'] > 0 AND $row['status'] != 'нет в наличии') ? $row['delivery'] + $row['quantity'] * $row['cost'] : 0;
			}
			$info = 'full';
			if ($this->_data['role']['name'] == 'performer') {
				$info = 'short';
			}
			$this->_body = array('status' => 'ok', 'info' => $info, 'type' => $this->request->post('action'), 'cost' => $this->_data['all_cost'], 'load' => URL::site('book/getitems/' . $this->request->post('orderid')));
		}
		else {
			$this->_data['rows'] = Model::factory('Book')->get_data('items', NULL, $this->_data['orderid']);
			$this->_data['all_cost'] = 0;
			foreach ($this->_data['rows'] as &$row) {
				$this->_data['all_cost'] += ($row['quantity'] > 0 AND $row['status'] != 'нет в наличии') ? $row['delivery'] + $row['quantity'] * $row['cost'] : 0;
			}
			$this->_data['order'] = Model::factory('Book')->get_order($this->_data['orderid']);
			$this->_data['enum'] = Model::factory('Book')->enum_values('items', 'status');
			$this->_data['items_table'] = View::factory('Book/items/table', $this->_data);
			$this->_data['title'] = 'Заказ #' . $this->_data['orderid'] . ' "' . $this->_data['order']['name'] . '"';
			$this->_body = View::factory('Book/items', $this->_data);
		}
	}

	public function action_orders() {
		// если метод запроса POST и выполнен с использованием AJAX
		if ($this->request->method() == Request::POST AND $this->request->is_ajax() AND $this->request->post('action') == 'complete') {
			$this->_json = TRUE;
			if (Model::factory('Book')->update($this->_data['action'], array('id' => $this->_data['orderid']), array('complete' => 'готов'))) {
				$this->_data['userinfo'] = Model::factory('Book')->get_userinfo(array(9));
				$this->_data['order'] = Model::factory('Book')->get_order($this->_data['orderid']);
				$this->_data['rows'] = Model::factory('Book')->get_data('items', NULL, $this->_data['orderid']);
					$message = array(
						'subject' => 'Новый заказ готов для покупки!',
						'body' => View::factory('email/' . $this->_data['action'].'_complete', $this->_data)->render(),
						'from' => array('noreply@lidocs.ru' => 'LIDOCS.RU'),
						'to' => array($this->_data['userinfo']['email'] => $this->_data['userinfo']['username'],'evgeniy@vlask.in' => 'Евгений')
					);
					Model::factory('Book')->into_stack(serialize($message));
				$this->_body = array('status' => 'ok');
			}
			else {
				$this->_body = array('status' => 'error');
			}

		}
		elseif ($this->request->method() == Request::POST AND $this->request->is_ajax() AND $this->request->post('action') == 'delete') {
			$this->_json = TRUE;
			Model::factory('Book')->delete($this->_data['action'], array('id' => $this->_data['orderid']));
			$this->_body = array('status' => 'ok');
		}
		elseif ($this->request->method() == Request::POST AND $this->request->is_ajax() AND $this->request->post('action') == 'edit') {
			$this->_json = TRUE;
			$this->_data['order'] = Model::factory('Book')->get_order($this->_data['orderid']);
			$this->_body = array('status' => 'ok', 'type' => $this->request->post('action'), 'name' => $this->_data['order']['name'], 'comment' => $this->_data['order']['comment']);
		}
		elseif ($this->request->method() == Request::POST AND $this->request->is_ajax() AND $this->request->post('action') == 'status') {
			$this->_json = TRUE;
			if (Model::factory('Book')->update($this->_data['action'], array('id' => $this->_data['orderid']), array('status' => $this->request->post('status')))) {
				$this->_data['order'] = Model::factory('Book')->get_order($this->_data['orderid']);
				$this->_data['status'] = $this->request->post('status');
				$this->_data['userinfo'] = Model::factory('Book')->get_userinfo($this->_data['orderid']);
				$this->_data['rows'] = Model::factory('Book')->get_data('items', NULL, $this->_data['orderid']);
				$this->_data['all_cost'] = 0;
				foreach ($this->_data['rows'] as &$row) {
					$this->_data['all_cost'] += ($row['quantity'] > 0 AND $row['status'] != 'нет в наличии') ? $row['delivery'] + $row['quantity'] * $row['cost'] : 0;
				}
				if ($this->_data['userinfo'] != FALSE) {
					$message = array(
						'subject' => 'Изменение статуса вашего заказа',
						'body' => View::factory('email/' . $this->_data['action'], $this->_data)->render(),
						'from' => array('noreply@lidocs.ru' => 'LIDOCS.RU'),
						'to' => array($this->_data['userinfo']['email'] => $this->_data['userinfo']['username'])
					);
					Model::factory('Book')->into_stack(serialize($message));
					$this->_body = array('status' => 'ok');
				}
				else {
					$this->_body = array('status' => 'error');
				}
			}
			else {
				$this->_body = array('status' => 'error');
			}
		}
		elseif ($this->request->method() == Request::POST AND $this->request->is_ajax()) {
			$this->_json = TRUE;
			// проверяем полученные данные
			$post = Validation::factory($this->request->post());
			// если проверка пройдена и card_id пустой (первое сохранение)
			if ($post->check()) {
				$data = array(
					'userid' => $this->user->id,
					'name' => $this->request->post('name'),
					'comment' => $this->request->post('comment')
				);
				Model::factory('Book')->set_order($data, $this->request->post('id', NULL));
			}
			$this->_body = array('status' => 'ok', 'type' => $this->request->post('action'), 'load' => '/book/getorders');
		}
		else {
			if ($this->_data['role']['name'] == 'performer') {
				$this->_data['rows'] = Model::factory('Book')->get_data('orders');
			}
			else {
				$this->_data['rows'] = Model::factory('Book')->get_data('orders', $this->user->id);
			}

			$this->_data['enum'] = Model::factory('Book')->enum_values('orders', 'status');
			$this->_data['orders_table'] = View::factory('Book/orders/table', $this->_data);
			$this->_data['title'] = 'Список заказов';
			$this->_body = View::factory('Book/orders', $this->_data);
		}
	}

	public function action_getorders() {
		// если метод запроса POST и выполнен с использованием AJAX
		if ($this->request->method() == Request::GET) {
			$this->_short = TRUE;
			if ($this->_data['role']['name'] == 'performer') {
				$this->_data['rows'] = Model::factory('Book')->get_data('orders');
			}
			else {
				$this->_data['rows'] = Model::factory('Book')->get_data('orders', $this->user->id);
			}
			$this->_data['enum'] = Model::factory('Book')->enum_values('orders', 'status');
			$this->_body = View::factory('Book/orders/table', $this->_data);
		}
	}

	public function action_getitems() {
		// если метод запроса POST и выполнен с использованием AJAX
		if ($this->request->method() == Request::GET) {
			$this->_short = TRUE;
			$this->_data['rows'] = Model::factory('Book')->get_data('items', NULL, $this->_data['orderid']);
			$this->_data['enum'] = Model::factory('Book')->enum_values('items', 'status');
			$this->_body = View::factory('Book/items/table', $this->_data);
		}
	}

	private function recalculate($orderid) {
		$sum = Model::factory('Book')->recalculate($orderid);
	}

	private function deleteimg($img){
		$ext = pathinfo($img, PATHINFO_EXTENSION);
		$dirs = array(
			'tmp/resize_1200x900/',
			'tmp/resize_80x80/',
			'tmp/resize_h100/',
			'tmp/resize_h80/',
			'tmp/',
		);
		foreach($dirs as &$dir){
		$img = str_replace('.'.$ext,'',$img);
			if (file_exists(DOCROOT.$dir.$img)){
				unlink(DOCROOT.$dir.$img);
			}
		}
	}

}

// End Book